package controller

import (
	"blogger/dao"
	"blogger/model"
	"github.com/gin-gonic/gin"
	"net/http"
	"strconv"
	"time"
)

// 跳转到写文章页面
func Article(c *gin.Context) {
	// 判断是否登录
	isLogin := IsLogin(c)
	c.HTML(http.StatusOK, "writeArticle.html", gin.H{
		"isLogin": isLogin,
	})
}

// 发布文章
func AddArticle(c *gin.Context) {
	articleDetail := &model.ArticleDetail{}
	articleDetail.CreateTime = time.Now().Local()
	if err := c.ShouldBindJSON(articleDetail); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"error":   err.Error(),
			"message": "参数错误",
		})
		return
	}
	// 调用添加方法
	err := dao.AddArticle(articleDetail)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"isSuccess": false,
			"message": "添加失败",
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"isSuccess": true,
		"message": "添加成功",
	})
}

// 文章详情页
func ArticleDetail(c *gin.Context) {
	// 判断是否登录
	isLogin := IsLogin(c)
	// 详情页文章id
	id, _ := strconv.Atoi(c.Query("articleId"))
	articleDetail, err := dao.GetArticleDetailById(id)
	if err != nil {
		panic(err)
		return
	}
	c.HTML(http.StatusOK, "articleDetail.html", gin.H{
		"articleDetail": articleDetail,
		"isLogin": isLogin,
	})
}